import axios from 'axios';
import {ElNotification, ElMessageBox, ElMessage, ElLoading} from 'element-plus';
import sysConfig from "@/config";
import tool from '@/utils/tool';
import router from '@/router';

axios.defaults.baseURL = ''

axios.defaults.timeout = sysConfig.TIMEOUT

// HTTP request 拦截器
axios.interceptors.request.use(
	(config) => {
		let token = tool.cookie.get("TOKEN");
		if(token){
			config.headers[sysConfig.TOKEN_NAME] = sysConfig.TOKEN_PREFIX + token
		}
		if(!sysConfig.REQUEST_CACHE && config.method == 'get'){
			config.params = config.params || {};
			config.params['_'] = new Date().getTime();
		}
		Object.assign(config.headers, sysConfig.HEADERS)
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// HTTP response 拦截器
axios.interceptors.response.use(
	(response) => {
		const data = response.data;
		switch(data.code){
			case 401:
				if(tool.data.get("INVALID_PERMISSION_MESSAGE"))return;
				ElMessageBox.alert(data.message, '无权限访问', {
					confirmButtonText: '退出重新登录',
					type: 'error',
					center: true,
					callback: () => {
						tool.data.clear();
						router.replace({path: '/login'});
					},
				})
				tool.data.set("INVALID_PERMISSION_MESSAGE",true);
				break
			case 403:
				// 没有权限
				ElMessage.error({
					title: '权限错误',
					message: data.message || "Status:403，服务器发生错误！"
				});
				break;
			case 500:
				ElMessage.error({
					grouping: true,
					title: '请求错误',
					message: data.message || "Status:500，服务器发生错误！"
				});
				break;
			default:
				return response;
		}
		return response;
	},
	(error) => {
		if (error.response) {
			ElNotification.error({
				title: '请求错误',
				message: error.toString() || `Status:${error.response.status}，未知错误！`
			});
		} else {
			ElNotification.error({
				title: '请求错误',
				message: "请求服务器无响应！"
			});
		}
		return Promise.reject(error.response);
	}
);

var http = {

	/** get 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} params
	 * @param  {参数} config
	 */
	get: function(url, params={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'get',
				url: url,
				params: params,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** post 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	post: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'post',
				url: url,
				data: data,
				headers:{
					'Content-Type': 'application/json',
				},
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},
	/** post 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	upload: function(url, data={}, config={}) {
	return new Promise((resolve, reject) => {
		axios({
			method: 'post',
			url: url,
			data: data,
			...config
		}).then((response) => {
			resolve(response.data);
		}).catch((error) => {
			reject(error);
		})
	})
},
	/** put 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	put: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'put',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** patch 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	patch: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'patch',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** delete 请求
	 * @param  {接口地址} url
	 * @param  {请求参数} data
	 * @param  {参数} config
	 */
	delete: function(url, data={}, config={}) {
		return new Promise((resolve, reject) => {
			axios({
				method: 'delete',
				url: url,
				data: data,
				...config
			}).then((response) => {
				resolve(response.data);
			}).catch((error) => {
				reject(error);
			})
		})
	},

	/** jsonp 请求
	 * @param  {接口地址} url
	 * @param  {JSONP回调函数名称} name
	 */
	jsonp: function(url, name='jsonp'){
		return new Promise((resolve) => {
			var script = document.createElement('script')
			var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
			script.id = _id
			script.type = 'text/javascript'
			script.src = url
			window[name] =(response) => {
				resolve(response)
				document.getElementsByTagName('head')[0].removeChild(script)
				try {
					delete window[name];
				}catch(e){
					window[name] = undefined;
				}
			}
			document.getElementsByTagName('head')[0].appendChild(script)
		})
	},
	 download : function (url, params={}, config={}){
		 const msg = ElLoading.service({
			 lock: true,
			 text: '正在导出',
			 background: 'rgba(0, 0, 0, 0.7)',
		 })
		return axios({
			method: 'post',
			url: url,
			data: params,
			transformRequest: [function (data) {
				let ret = '';
				for (let it in data) {
					ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
				}
				return ret;
			}],
			responseType: 'blob',
			...config
		}).then(res =>{
			console.log(res.headers)
			msg.close()
			let blob = new Blob([res.data], {type: res.data.type})
			let downloadElement = document.createElement('a')
			let href = window.URL.createObjectURL(blob); //创建下载的链接
			downloadElement.href = href;

			downloadElement.download = decodeURI(res.headers.filename)+"_"+new Date().getTime()+".xlsx"; //下载后文件名
			document.body.appendChild(downloadElement);
			downloadElement.click(); //点击下载
			document.body.removeChild(downloadElement); //下载完成移除元素
			window.URL.revokeObjectURL(href); //释放blob对象
		});
	}
}

export default http;
